//
//  ViewController.m
//  01-掌握-登录小案例
//
//  Created by xmg on 16/4/8.
//  Copyright © 2016年 haibo. All rights reserved.
//

#import "ViewController.h"
#import "SVProgressHUD.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *pwd;

@end

@implementation ViewController

- (IBAction)loginBtn:(id)sender {
    //得到用户的名称和密码
    NSString * userName = self.userName.text;
    NSString * pwd = self.pwd.text;
    if (userName == nil) {
        [SVProgressHUD showErrorWithStatus:self.userName.placeholder];
        return;
    }
    if (pwd == nil) {
        [SVProgressHUD showErrorWithStatus:self.pwd.placeholder];
        return;
    }
    //设置请求路径
    NSURL * url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
    //设置请求对象
    NSMutableURLRequest * requeue = [NSMutableURLRequest requestWithURL:url];
    //更改请求方法
    requeue.HTTPMethod = @"POST";
    //设置请求头
    NSString * httpBody = [NSString stringWithFormat:@"username=%@&pwd=%@&type=JSON",self.userName.text,self.pwd.text];
    requeue.HTTPBody = [httpBody dataUsingEncoding:NSUTF8StringEncoding];
    //获取回话对象
    NSURLSession * session = [NSURLSession sharedSession];
    //创建回话
    [[session dataTaskWithRequest:requeue completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        //解析数据
//        NSString * resultStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        //解析JSON数据
       NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSLog(@"%@",dict);
        if ([dict objectForKey:@"error"]) {
            [SVProgressHUD showErrorWithStatus:@"登录失败"];
        }
        if ([dict objectForKey:@"success"]) {
            [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
        }
        
    }]resume];
    
    //弹出登录
    [SVProgressHUD showWithStatus:@"正在登录"];
}


@end
